import { onMounted, nextTick, ref } from 'vue';
import { useInjectSiderMenu } from '../context';
import { useMenuStore } from '@/stores/menu-store';
import { openMenu } from '@/hooks/use-menu';
import Sortable from 'sortablejs';

export function useSiderMenuList({ props, context }) {
  const { emit } = context;
  const sortEl = ref();
  const siderMenu = useInjectSiderMenu();
  const menuStore = useMenuStore();
  // 点击菜单
  const clickMenu = (menu) => {
    openMenu(menu.id);
  };
  // 点击删除菜单
  const clickRemoveClick = (menu) => {
    emit('remove', menu.id);
  };

  if (props.sort) {
    onMounted(() => {
      nextTick(() => {
        Sortable.create(sortEl.value, {
          handle: '.menu-list-item-move',
          forceFallback: true,
          ghostClass: 'menu-list-item-sortable-ghost',
          dragClass: 'menu-list-item-sortable-drag',
          onEnd: (sortableEvent) => {
            emit('sort', sortableEvent);
          },
        });
      });
    });
  }

  return { siderMenu, menuStore, sortEl, clickMenu, clickRemoveClick };
}
